package com.yc.RSS.reader;

import com.yc.RSS.buffer.NewsBuffer;
import com.yc.RSS.writer.NewsWriterTask;
import org.apache.log4j.Logger;

import javax.naming.Name;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author zwei
 * @create 2024-07-24 17:03
 */
public class NewsSystem implements Runnable{
    private Logger logger=Logger.getLogger(NewsWriterTask.class);

    private String sourcesPath;     //源RSS的地址
    private ScheduledThreadPoolExecutor executor;   //定时调度的线程池
    private NewsBuffer buffer;
    public NewsSystem(String sourcesPath){
        this.sourcesPath=sourcesPath;
        this.executor=new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors());
        buffer=new NewsBuffer();
    }
    @Override
    public void run() {
        //消费任务
        NewsWriterTask writerTask=new NewsWriterTask(buffer);
        Thread thread=new Thread(writerTask);
        thread.start();

        //生产者任务   读取sources.txt中的RSS源  有几个源就启动几个线程
        Path file=Paths.get(sourcesPath);
        try (BufferedReader reader=new BufferedReader(   new FileReader(  file.toFile()))){
            String line=null;
            while ( (line=reader.readLine())!=null ){
                String[]strs=line.split(";");
                if (strs!=null&&strs.length==2){
                    String rssname=strs[0];
                    String url=strs[1];
                    //创建生产者任务
                    NewProductTask productTask=new NewProductTask(url, rssname,buffer);
                    //每隔10分钟执行一次
                    this.executor.scheduleWithFixedDelay( productTask,0,10, TimeUnit.MINUTES);
                }
            }
        } catch ( Exception e ){
            logger.error(e);
        }
    }
}
